package com.yanqu.road.web.controller.usercenter.logic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.servercenter.*;
import com.yanqu.road.entity.servercenter.tabnotice.ChannelTabNotice;
import com.yanqu.road.entity.web.HttpGameWebParam;
import com.yanqu.road.entity.web.RecommendServerReturnParam;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.logic.redis.RedisManger;
import com.yanqu.road.logic.redis.RedisUserServerList;
import com.yanqu.road.server.helper.ErrorCodeHelper;
import com.yanqu.road.server.manger.*;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.mgr.ChannelNoticeMgr;
import com.yanqu.road.web.mgr.ChannelTabNoticeMgr;
import com.yanqu.road.web.mgr.RoleCreateCountMgr;
import com.yanqu.road.web.util.IpAddressHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.Tuple;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

public class ServerListHelper {

    private static Logger logger = LogManager.getLogger(ServerListHelper.class.getName());

    /**
     * 填充区服列表、渠道公告、分流推荐服务器
     * @param resultObj
     * @param ip
     * @param openId
     * @param channelId
     * @param serverList
     * @param language
     * @param isMarkStrUrlEncoder
     */
    public static void dealServerList(JSONObject resultObj, String ip, String openId, int channelId, List<ServerInfo> serverList,
                                      String language, boolean isMarkStrUrlEncoder, boolean whiteAccount,List<Long> hasPreRoleServerIdList,
                                      String appId){
        //提审IP黑名单 永远只拿到提审服
        if (WhiteIpMgr.isBlackIp(ip)) {
            resultObj.put("isTishen", true);
        }

        /**
         * 用户历史登录列表
         */
        boolean isNewUser = false;
        try {
            if (!StringUtils.isNullOrEmpty(openId)) {
                Set<String> result = RedisUserServerList.getPlayerServerList(openId);
                if (null != result) {
                    resultObj.put("userServerList", JSON.toJSONString(result));

                    //获取玩家区服的登录时间
                    Set<Tuple> loginTimeSet = RedisUserServerList.getPlayerServerListTuple(openId);
                    Map<String, Long> loginTimeMap = new HashMap<>();
                    for (Tuple tuple : loginTimeSet) {
                        loginTimeMap.put(tuple.getElement(), (long) tuple.getScore());
                    }
                    resultObj.put("userServerLoginTimeList", JSON.toJSONString(loginTimeMap));
                } else {
                    resultObj.put("userServerList", new JSONObject().toString());
                    resultObj.put("userServerLoginTimeList", new JSONObject().toString());
                }

                if (result == null || result.size() == 0) {
                    isNewUser = true;
                }
            }
        } catch (Exception e) {
            resultObj.put("userServerList", new JSONObject().toString());
            resultObj.put("userServerLoginTimeList", new JSONObject().toString());
        }


        JSONArray serverListArr = new JSONArray();
        JSONArray activityListArr = new JSONArray();

        for (ServerInfo serverInfo : serverList) {
            if (serverInfo.getServerType() == ServerListMgr.SERVER_TYPE_ACTIVITY) {
                activityListArr.add(ServerListMgr.parseServerJson(serverInfo, language, isMarkStrUrlEncoder, whiteAccount,hasPreRoleServerIdList.contains(serverInfo.getServerId())));
            }else {
                serverListArr.add(ServerListMgr.parseServerJson(serverInfo, language, isMarkStrUrlEncoder, whiteAccount, hasPreRoleServerIdList.contains(serverInfo.getServerId())));
            }
        }

        resultObj.put("serverList", serverListArr.toString());
        resultObj.put("activityServerList", activityListArr.toString());
        resultObj.put("hideTime", ServerListMgr.getHideTime(channelId) / 1000);

        ChannelNotice channelNotice = ChannelNoticeMgr.getChannelNotice(channelId, language);
        JSONObject noticeObj = ChannelNoticeMgr.parseNoticeJson(channelNotice);
        resultObj.put("notice", noticeObj.toString());

        // 页签公告
        ChannelTabNotice channelTabNotice = ChannelTabNoticeMgr.getChannelTabNotice(channelId, appId, language);
        resultObj.put("tabNotice", ChannelTabNoticeMgr.parseTabNoticeToJsonStr(channelTabNotice));

        /**
         * 新用户分流策略 推荐到不同的区服
         */
        boolean isChannelOpenSplitFlow = ServerListMgr.isChannelOpenSplitFlow(channelId);
        resultObj.put("openSplitFlow", isChannelOpenSplitFlow ? 1 : 0);

//        RecommendServerReturnParam recommendServerReturnParam = RegisterPlayerNumMgr.getRecommendServerInfo(serverList);
        RecommendServerReturnParam recommendServerReturnParam = RoleCreateCountMgr.getRecommendServerInfo(serverList);
        if (recommendServerReturnParam != null) {
            resultObj.put("recommendServerIdList", StringUtils.listToString(recommendServerReturnParam.getServerIdList(), ","));
        }

        if (isChannelOpenSplitFlow && isNewUser) {
            // 新用户分流
            if (recommendServerReturnParam != null) {
                resultObj.put("recommendServer", ServerListMgr.parseServerJson(recommendServerReturnParam.getServerInfo(), language, isMarkStrUrlEncoder, whiteAccount,hasPreRoleServerIdList.contains(recommendServerReturnParam.getServerInfo().getServerId())));
            }
        }
    }

    public static JSONObject getPackageServerList(HttpServletRequest request, HttpGameWebParam httpGameWebParam, boolean isMarkStrUrlEncoder) {
        /**
         * 参数解析
         */
        logger.info("request packageServerList");
        JSONObject paramObj = httpGameWebParam.getParamObj();
        String param = httpGameWebParam.getParam();
        String language = httpGameWebParam.getLanguage();

        String openId;
        String platformUserId;
        String packageVersion;
        String packageMark;
        String hotPackVersion;
        String appId = null;
        int clientChannelId;
        try {
            openId = paramObj.getString("openId");
            platformUserId = paramObj.getString("platformUserId");
            packageVersion = paramObj.getString("packageVersion");
            packageMark = paramObj.getString("packageMark");
            hotPackVersion = paramObj.getString("hotPackVersion");
            clientChannelId = paramObj.getInteger("channelId");
        } catch (Exception e) {
            logger.error("packageServerList request json格式出错！ json 字符串param为{}", param, e);
            return getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language, isMarkStrUrlEncoder);
        }
        if(null == hotPackVersion || null == packageVersion || null == packageMark){
            logger.error("packageServerList request lost argument！param为{}", param);
            return getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language, isMarkStrUrlEncoder);
        }

        String ip = IpAddressHelper.getIpAddr(request);

        PackageMark packageMarkData = PackageVersionMgr.getPackageMark(packageMark);
        if(null == packageMarkData){
            logger.error("packageServerList packageMark no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
            return getResultObj(GameErrorCode.E_PACKAGE_MARK_NO_FOUND, language, isMarkStrUrlEncoder);
        }

        boolean isWhiteUser = ServerListMgr.isWhiteUser(ip, false, platformUserId);
        int forwardServer = 0;
        String clientLoginVerson = ""; // 给客户端判断允许客户端登录的版本

        try {
            appId = paramObj.getString("appId");
        } catch (Exception e) {
            logger.error("appid is null json 字符串param为{}", param, e);
        }
        if (appId != null) {
            AppIdChaneelInfo appIdChaneelInfo = ServerListMgr.getAppIdChaneelInfo(appId);
            if (appIdChaneelInfo != null) {
                forwardServer = appIdChaneelInfo.getForwardServer();
                clientLoginVerson = appIdChaneelInfo.getClientLoginVersion();
            }
        }

        boolean isNeedOldDeal = isNeedOldDeal(packageMark, isWhiteUser, forwardServer);

        int channelId = packageMarkData.getChannelId();
        int logoOpen = 1; // logo信息厂商开关
        int userOpen = 1;
        int mUserOpen = 1;
        int secretAgreementOpen = 0;
        String secretUrl = "";
        String agreementUrl = "";
        String updateDeleteUrl = "";
        String logOutUrl = "";
        String companyInfo = "";
        boolean isReview = false;
        boolean isHotPackUpdateCheck = false;
        int customerButtonShow = 0;     //是否显示客服按钮，0：隐藏；1：显示

        if(isNeedOldDeal){
            //获取包体信息
            PackageVersion versionData = PackageVersionMgr.getPackageVersion(packageMark, packageVersion);
            if(null == versionData){
                logger.info("packageServerList packageVersion no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
                return getResultObj(GameErrorCode.E_PACKAGE_VERSION_NO_FOUND, language, isMarkStrUrlEncoder);
            }
            //获取热更包体信息
            HotPackVersion hotPackData = HotPackVersionMgr.getHotPackVersion(packageMark, packageVersion, hotPackVersion);
            if(null == hotPackData){
                logger.info("packageServerList hotPackVersion no find, packageMark:{}, packageVersion:{}, hotPackVersion:{}",
                        packageMark, packageVersion, hotPackVersion);
                return getResultObj(GameErrorCode.E_HOT_PACK_VERSION_NO_FOUND, language, isMarkStrUrlEncoder);
            }
            isReview = HotPackVersionMgr.isHotPackVersionReview(hotPackData, appId, channelId);
            isHotPackUpdateCheck = hotPackData.isHotPackUpdateCheck();
        }else {
            //获取热更包体信息
            HotfixVersion hotPackData = HotPackVersionMgr.getHotfixVersion(packageMark, packageVersion, hotPackVersion, isWhiteUser, forwardServer);
            isReview = HotPackVersionMgr.isHotfixVersionReview(hotPackData, appId, channelId);
            isHotPackUpdateCheck = isHotPackUpdateCheck(packageVersion);
        }
        List<String> hideMarks = new ArrayList<>();
        if (eChannelType.isMainLandChannel(channelId)) {
            try {
                // 需要对appId做区分
                int realChannelId = ServerListMgr.getChannelIdByAppId(appId);
                if (realChannelId > 0) {
                    channelId = realChannelId;
                    logger.info("translate  {} to {}", clientChannelId, channelId);
                }

                AppIdChaneelInfo appIdChaneelInfo = ServerListMgr.getAppIdChaneelInfo(appId);
                logoOpen = appIdChaneelInfo == null ? 1 : appIdChaneelInfo.getLogoOpen();
                userOpen = appIdChaneelInfo == null ? 1 : appIdChaneelInfo.getUserOpen();
                mUserOpen = appIdChaneelInfo == null ? 1 : appIdChaneelInfo.getMjbUserOpen();
                secretAgreementOpen = appIdChaneelInfo == null ? 0 : appIdChaneelInfo.getSecretAgreementOpen();
                secretUrl = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getSecrteUrl();
                agreementUrl = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getAgreementUrl();
                companyInfo = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getCompanyInfo();
                hideMarks = appIdChaneelInfo == null ? new ArrayList<>() : appIdChaneelInfo.getHideMarks();
                updateDeleteUrl = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getUpdateDeleteUrl();
                logOutUrl = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getLogOutUrl();
                customerButtonShow = appIdChaneelInfo == null ? 0 : appIdChaneelInfo.getCustomerButtonShow();
            } catch (Exception e) {
                logger.error("appid is null json 字符串param为{}", param, e);
            }
        }

        //设置提审状态
        JSONObject resultObj = getResultObj(0, language, isMarkStrUrlEncoder);
        resultObj.put("isTishen", isReview);
        resultObj.put("hotPackUpdateCheck", isHotPackUpdateCheck);
        resultObj.put("logoOpen", logoOpen);
        resultObj.put("isUserOpen", userOpen);
        resultObj.put("mUserOpen", mUserOpen);
        resultObj.put("saOpen", secretAgreementOpen);
        resultObj.put("secretUrl", secretUrl);
        resultObj.put("agreementUrl", agreementUrl);
        resultObj.put("updateDeleteUrl", updateDeleteUrl);
        resultObj.put("logOutUrl", logOutUrl);
        resultObj.put("customerButtonShow", customerButtonShow);

        // 如果没有配置客户端登录版本则不下发
        if (!StringUtils.isNullOrEmpty(clientLoginVerson)) {
            resultObj.put("clientLoginVersion", clientLoginVerson);
        }

        //新增配置版本
        String configVersion = "";
        ChannelHotUpdateConfigVersion hotUpdateConfigVersion = ChannelHotUpdateConfigMgr.getChannelHotUpdateConfigVersion(
                packageMark, hotPackVersion, isWhiteUser ? 0 : (forwardServer > 0 ? 1 : 2));
        if(hotUpdateConfigVersion != null){
            configVersion = hotUpdateConfigVersion.getUpdateVersion();
        }
        resultObj.put("gameconfigV", configVersion);

        try {
            String com = URLEncoder.encode(companyInfo, "UTF-8");
            resultObj.put("companyInfo", com.replace("+", "%20"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ChannelInfo channelInfo = ServerListMgr.getChannelInfo(channelId);
        int loadingBgSwitch = 0;
        String clientSwitch = "";
        if (channelInfo == null) {
            resultObj.put("openTime", 0);
        } else {
            loadingBgSwitch = channelInfo.getLoadingBgSwitch();
            resultObj.put("openTime", channelInfo.getOpenTime());
            if(!StringUtils.isNullOrEmpty(channelInfo.getClientSwitch())){
                clientSwitch = channelInfo.getClientSwitch();
            }
        }

        //loading页背景开关
        resultObj.put("loadingBgSwitch", loadingBgSwitch);
        resultObj.put("ClientSwitch", clientSwitch);

        if (isReview || WhiteIpMgr.isPlayerWhiteIp(ip) || PlatformUserIdMgr.isPlatformUserIdPass(platformUserId)) {
            resultObj.put("openTime", 0);
        }

        /**
         * 获取服务器列表
         */
        List<ServerInfo> serverList = ServerListMgr.getPackageServerList(packageMark, isReview, ip, platformUserId, channelId, appId);

        boolean whiteAccount = false;
        if (WhiteIpMgr.isPlayerWhiteIp(ip) || PlatformUserIdMgr.isPlatformUserIdPass(platformUserId)) {
            whiteAccount = true;
        }

        if (!WhiteIpMgr.isPlayerWhiteIp(ip) && !PlatformUserIdMgr.isPlatformUserIdPass(platformUserId)) {
            // 如果是非白名单 特殊处理
//            try {
//                if (appId != null && appId.equals("37h5") && !StringUtils.isNullOrEmpty(openId)) {
////                    Set<String> result = RedisUserServerList.getPlayerServerList(openId);
////                    if (result == null || result.size() == 0) {
//                    if (!ServerListMgr.getHideJinYuMap().containsKey(platformUserId)){
//                        // 新用户屏蔽金玉满堂
//                        hideMarks.add("金玉满堂");
//                        logger.error("not login record {} {} {}", appId, openId, platformUserId);
//                    } else {
//                        // 老用户屏蔽除了金玉满堂以外的标签
//                        for (ServerInfo serverInfo : serverList) {
//                            if (serverInfo.getMarkStr().equals("金玉满堂")) {
//                                continue;
//                            }
//                            if (!hideMarks.contains(serverInfo.getMarkStr())) {
//                                hideMarks.add(serverInfo.getMarkStr());
//                            }
//                        }
//                    }
//                }
//            } catch (Exception var29) {
//
//            }

//            try {
//                if (channelId == eChannelType.Hun1.getValue() || channelId == eChannelType.Hun2.getValue()) {
//                    // 非白名单并且是混服1混服2 并且packageVersion 小于2.X的 不能拿到服务器列表
//                    List<Integer> versionList = StringUtils.stringToIntegerList(packageVersion, "\\.");
//                    if (versionList.get(0) < 2) {
//                        serverList = new ArrayList<>();
//                    }
//                }
//            } catch (Exception ex) {
//                logger.error("versionList error");
//            }

        }



        // 通过appid 设置隐藏标签区服
        List<ServerInfo> tempServerList = new ArrayList<>();

        if (!WhiteIpMgr.isPlayerWhiteIp(ip) && !PlatformUserIdMgr.isPlatformUserIdPass(platformUserId)) {
            // 非白名单
            for (ServerInfo serverInfo : serverList) {
                if (hideMarks.contains(serverInfo.getMarkStr())) {
                    // 如果包含在隐藏标签内
                    continue;
                }

                tempServerList.add(serverInfo);
            }
        } else {
            // 白名单
            tempServerList = serverList;
        }
//        List<Long> hasCreateRoleServerIdList = UserBussiness.getUserPreServerList(openId);
        Set<String> userRegisterServerList =
                RedisManger.getRedisUtil().zmember("PLAYERFISHSERVER"+ "_" + openId,0,System.currentTimeMillis()/1000);
        List<Long> hasCreateRoleServerIdList = new ArrayList<>();
        for(String serverIdStr : userRegisterServerList){
            hasCreateRoleServerIdList.add(Long.valueOf(serverIdStr));
        }

        /**
         * 填充区服列表、渠道公告、分流处理
         */
        ServerListHelper.dealServerList(resultObj, ip, openId, channelId, tempServerList, language, isMarkStrUrlEncoder, whiteAccount,
                hasCreateRoleServerIdList, appId);

        if (eChannelType.isMainLandChannel(channelId)) {
            try {
                ChannelNotice channelNotice = ChannelNoticeMgr.getChannelNotice(appId, language);
                JSONObject noticeObj = ChannelNoticeMgr.parseNoticeJson(channelNotice);
                resultObj.put("notice", noticeObj.toString());
            } catch (Exception ex) {
                logger.error("mainland notice error,param:{},error:", param, ex);
            }
        }

        // 页签公告
        ChannelTabNotice channelTabNotice = ChannelTabNoticeMgr.getChannelTabNotice(channelId, appId, language);
        resultObj.put("tabNotice", ChannelTabNoticeMgr.parseTabNoticeToJsonStr(channelTabNotice));

        //预创角，倒计时要用到服务器时间
        resultObj.put("nowTime",System.currentTimeMillis());
        resultObj.put("timeZone", LocalDateTimeHelper.getDefaultTimeZone());
        resultObj.put("isWhite", isWhiteUser);

        //老玩家回归，引导到新服创建新号配置天数
        resultObj.put("userBackNewServerDay", ChannelConfig.USER_BACK_NEW_SERVER_DAY);

        return  resultObj;
    }

    /**
     * 越南专用
     * desc :
     * 请求参数去掉了hotPackVersion等于packageVersion
     * 返回值最后统一处理替换
     */
    public static JSONObject getPackageServerListVN2(HttpServletRequest request, HttpGameWebParam httpGameWebParam, boolean isMarkStrUrlEncoder) {
        /**
         * 参数解析
         */
        logger.info("request packageServerListVN2");
        JSONObject paramObj = httpGameWebParam.getParamObj();
        String param = httpGameWebParam.getParam();
        String language = httpGameWebParam.getLanguage();

        String openId;
        String platformUserId;
        String packageVersion;
        String packageMark;
        String hotPackVersion;
        String appId = null;
        int clientChannelId;
        try {
            openId = paramObj.getString("openId");
            platformUserId = paramObj.getString("platformUserId");
            packageVersion = paramObj.getString("packageVersion");
            packageMark = paramObj.getString("packageMark");
            hotPackVersion = packageVersion; // 越南特殊处理
            clientChannelId = paramObj.getInteger("channelId");
        } catch (Exception e) {
            logger.error("packageServerListVN2 request json格式出错！ json 字符串param为{}", param, e);
            return getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language, isMarkStrUrlEncoder);
        }
        if (null == hotPackVersion || null == packageVersion || null == packageMark) {
            logger.error("packageServerListVN2 request lost argument！param为{}", param);
            return getResultObj(GameErrorCode.E_REQUEST_ARGUMENT_ERROR, language, isMarkStrUrlEncoder);
        }

        String ip = IpAddressHelper.getIpAddr(request);

        PackageMark packageMarkData = PackageVersionMgr.getPackageMark(packageMark);
        if (null == packageMarkData) {
            logger.error("packageServerListVN2 packageMark no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
            return getResultObj(GameErrorCode.E_PACKAGE_MARK_NO_FOUND, language, isMarkStrUrlEncoder);
        }

        boolean isWhiteUser = ServerListMgr.isWhiteUser(ip, false, platformUserId);
        int forwardServer = 0;
        String clientLoginVerson = ""; // 给客户端判断允许客户端登录的版本

        try {
            appId = paramObj.getString("appId");
        } catch (Exception e) {
            logger.error("appid is null json 字符串param为{}", param, e);
        }
        if (appId != null) {
            AppIdChaneelInfo appIdChaneelInfo = ServerListMgr.getAppIdChaneelInfo(appId);
            if (appIdChaneelInfo != null) {
                forwardServer = appIdChaneelInfo.getForwardServer();
                clientLoginVerson = appIdChaneelInfo.getClientLoginVersion();
            }
        }

        boolean isNeedOldDeal = isNeedOldDeal(packageMark, isWhiteUser, forwardServer);

        int channelId = packageMarkData.getChannelId();
        int logoOpen = 1; // logo信息厂商开关
        int userOpen = 1;
        int mUserOpen = 1;
        int secretAgreementOpen = 0;
        String secretUrl = "";
        String agreementUrl = "";
        String updateDeleteUrl = "";
        String logOutUrl = "";
        String companyInfo = "";
        boolean isReview = false;
        boolean isHotPackUpdateCheck = false;
        int customerButtonShow = 0;     //是否显示客服按钮，0：隐藏；1：显示

        if (isNeedOldDeal) {
            //获取包体信息
            PackageVersion versionData = PackageVersionMgr.getPackageVersion(packageMark, packageVersion);
            if (null == versionData) {
                logger.info("packageServerListVN2 packageVersion no find, packageMark:{}, packageVersion:{}", packageMark, packageVersion);
                return getResultObj(GameErrorCode.E_PACKAGE_VERSION_NO_FOUND, language, isMarkStrUrlEncoder);
            }
            //获取热更包体信息
            HotPackVersion hotPackData = HotPackVersionMgr.getHotPackVersion(packageMark, packageVersion, hotPackVersion);
            if (null == hotPackData) {
                logger.info("packageServerListVN2 hotPackVersion no find, packageMark:{}, packageVersion:{}, hotPackVersion:{}",
                        packageMark, packageVersion, hotPackVersion);
                return getResultObj(GameErrorCode.E_HOT_PACK_VERSION_NO_FOUND, language, isMarkStrUrlEncoder);
            }
            isReview = HotPackVersionMgr.isHotPackVersionReview(hotPackData, appId, channelId);
            isHotPackUpdateCheck = hotPackData.isHotPackUpdateCheck();
        } else {
            //获取热更包体信息
            HotfixVersion hotPackData = HotPackVersionMgr.getHotfixVersion(packageMark, packageVersion, hotPackVersion, isWhiteUser, forwardServer);
            isReview = HotPackVersionMgr.isHotfixVersionReview(hotPackData, appId, channelId);
            isHotPackUpdateCheck = isHotPackUpdateCheck(packageVersion);
        }
        List<String> hideMarks = new ArrayList<>();
        if (eChannelType.isMainLandChannel(channelId)) {
            try {
                // 需要对appId做区分
                int realChannelId = ServerListMgr.getChannelIdByAppId(appId);
                if (realChannelId > 0) {
                    channelId = realChannelId;
                    logger.info("translate  {} to {}", clientChannelId, channelId);
                }

                AppIdChaneelInfo appIdChaneelInfo = ServerListMgr.getAppIdChaneelInfo(appId);
                logoOpen = appIdChaneelInfo == null ? 1 : appIdChaneelInfo.getLogoOpen();
                userOpen = appIdChaneelInfo == null ? 1 : appIdChaneelInfo.getUserOpen();
                mUserOpen = appIdChaneelInfo == null ? 1 : appIdChaneelInfo.getMjbUserOpen();
                secretAgreementOpen = appIdChaneelInfo == null ? 0 : appIdChaneelInfo.getSecretAgreementOpen();
                secretUrl = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getSecrteUrl();
                agreementUrl = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getAgreementUrl();
                companyInfo = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getCompanyInfo();
                hideMarks = appIdChaneelInfo == null ? new ArrayList<>() : appIdChaneelInfo.getHideMarks();
                updateDeleteUrl = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getUpdateDeleteUrl();
                logOutUrl = appIdChaneelInfo == null ? "" : appIdChaneelInfo.getLogOutUrl();
                customerButtonShow = appIdChaneelInfo == null ? 0 : appIdChaneelInfo.getCustomerButtonShow();
            } catch (Exception e) {
                logger.error("appid is null json 字符串param为{}", param, e);
            }
        }

        //设置提审状态
        JSONObject resultObj = getResultObj(0, language, isMarkStrUrlEncoder);
        resultObj.put("isTishen", isReview);
        resultObj.put("hotPackUpdateCheck", isHotPackUpdateCheck);
        resultObj.put("logoOpen", logoOpen);
        resultObj.put("isUserOpen", userOpen);
        resultObj.put("mUserOpen", mUserOpen);
        resultObj.put("saOpen", secretAgreementOpen);
        resultObj.put("secretUrl", secretUrl);
        resultObj.put("agreementUrl", agreementUrl);
        resultObj.put("updateDeleteUrl", updateDeleteUrl);
        resultObj.put("logOutUrl", logOutUrl);
        resultObj.put("customerButtonShow", customerButtonShow);
        resultObj.put("isWhite", isWhiteUser);

        // 如果没有配置客户端登录版本则不下发
        if (!StringUtils.isNullOrEmpty(clientLoginVerson)) {
            resultObj.put("clientLoginVersion", clientLoginVerson);
        }

        try {
            String com = URLEncoder.encode(companyInfo, "UTF-8");
            resultObj.put("companyInfo", com.replace("+", "%20"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ChannelInfo channelInfo = ServerListMgr.getChannelInfo(channelId);
        int loadingBgSwitch = 0;
        String clientSwitch = "";
        if (channelInfo == null) {
            resultObj.put("openTime", 0);
        } else {
            loadingBgSwitch = channelInfo.getLoadingBgSwitch();
            resultObj.put("openTime", channelInfo.getOpenTime());
            if(!StringUtils.isNullOrEmpty(channelInfo.getClientSwitch())){
                clientSwitch = channelInfo.getClientSwitch();
            }
        }

        //loading页背景开关
        resultObj.put("loadingBgSwitch", loadingBgSwitch);
        resultObj.put("ClientSwitch", clientSwitch);

        if (isReview || WhiteIpMgr.isPlayerWhiteIp(ip) || PlatformUserIdMgr.isPlatformUserIdPass(platformUserId)) {
            resultObj.put("openTime", 0);
        }

        /**
         * 获取服务器列表
         */
        List<ServerInfo> serverList = ServerListMgr.getPackageServerList(packageMark, isReview, ip, platformUserId, channelId, appId);

        boolean whiteAccount = false;
        if (WhiteIpMgr.isPlayerWhiteIp(ip) || PlatformUserIdMgr.isPlatformUserIdPass(platformUserId)) {
            whiteAccount = true;
        }

        if (!WhiteIpMgr.isPlayerWhiteIp(ip) && !PlatformUserIdMgr.isPlatformUserIdPass(platformUserId)) {
            // 原方法都注释掉了这边就不要了
        }


        // 通过appid 设置隐藏标签区服
        List<ServerInfo> tempServerList = new ArrayList<>();

        if (!WhiteIpMgr.isPlayerWhiteIp(ip) && !PlatformUserIdMgr.isPlatformUserIdPass(platformUserId)) {
            // 非白名单
            for (ServerInfo serverInfo : serverList) {
                if (hideMarks.contains(serverInfo.getMarkStr())) {
                    // 如果包含在隐藏标签内
                    continue;
                }

                tempServerList.add(serverInfo);
            }
        } else {
            // 白名单
            tempServerList = serverList;
        }

        /**
         * 填充区服列表、渠道公告、分流处理
         */
        ServerListHelper.dealServerList(resultObj, ip, openId, channelId, tempServerList, language, isMarkStrUrlEncoder, whiteAccount,
                new ArrayList<>(), appId);

        if (eChannelType.isMainLandChannel(channelId)) {
            try {
                ChannelNotice channelNotice = ChannelNoticeMgr.getChannelNotice(appId, language);
                JSONObject noticeObj = ChannelNoticeMgr.parseNoticeJson(channelNotice);
                resultObj.put("notice", noticeObj.toString());
            } catch (Exception ex) {
                logger.error("mainland notice error, param:{},error:", param, ex);
            }
        }

        // 页签公告
        ChannelTabNotice channelTabNotice = ChannelTabNoticeMgr.getChannelTabNotice(channelId, appId, language);
        resultObj.put("tabNotice", ChannelTabNoticeMgr.parseTabNoticeToJsonStr(channelTabNotice));

        // ========== 【越南替换参数】begin ==========

        resultObj.remove("hotPackUpdateCheck");
        resultObj.remove("isUserOpen");
        resultObj.remove("logoOpen");
        resultObj.remove("mUserOpen");
        resultObj.remove("saOpen");
        resultObj.remove("agreementUrl");
        resultObj.remove("companyInfo");
        resultObj.remove("customerButtonShow");
        resultObj.remove("logOutUrl");
        resultObj.remove("secretUrl");
        resultObj.remove("updateDeleteUrl");

        Object hideTime = resultObj.remove("hideTime");
        resultObj.put("serverHTime", hideTime);

        Object msg = resultObj.remove("msg");
        String msgStr = (String) msg;
        Object isTishen = resultObj.remove("isTishen");
        String isTishenStr = (boolean) isTishen ? "1" : "0";
        Object openSplitFlow = resultObj.remove("openSplitFlow");
        String openSplitFlowStr = String.valueOf((int) openSplitFlow);
        resultObj.put("msg", msgStr + isTishenStr + openSplitFlowStr);

        Object openTime = resultObj.remove("openTime");
        resultObj.put("serverTime", openTime);

        // ========== 【越南替换参数】end ==========


        return resultObj;
    }


    public static JSONObject getResultObj(int ret, String language, boolean isMarkStrUrlEncoder) {
        JSONObject resultObj = new JSONObject();
        resultObj.put("result", ret);
        if (0 == ret) {
            resultObj.put("msg", "Success");
        } else{
            if(isMarkStrUrlEncoder){
                String errorDesc = MultipleLanguageMgr.getContent(ErrorCodeHelper.ERROR_CODE_PREFIX + ret, language);
                try {
                    errorDesc = URLEncoder.encode(errorDesc, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                resultObj.put("msg", errorDesc);
            }else {
                resultObj.put("msg", MultipleLanguageMgr.getContent(ErrorCodeHelper.ERROR_CODE_PREFIX + ret, language));
            }
        }
        return resultObj;
    }

    public static boolean isHotPackUpdateCheck(String packageVersion){
        int ver1 = 0;
        int ver2 = 0;
        int ver3;
        if(!StringUtils.isNullOrEmpty(packageVersion)){
            String[] verArr = packageVersion.split("\\.");
            if(verArr.length >= 3) {
                ver1 = StringUtils.string2intSafe(verArr[0], 0);
                ver2 = StringUtils.string2intSafe(verArr[1], 0);
                ver3 = StringUtils.string2intSafe(verArr[2], 0);
            }
        }
        if(ver1 > 2){
            return true;
        }else if(ver1 == 2){
            return ver2 >= 2;
        }else {
            return false;
        }
    }

    public static boolean isNeedOldDeal(String packageMark, boolean isWhiteUser, int forwardServer){
        boolean needOldDeal = false;
        HotfixUpdateInfo hotfixUpdateInfo = HotPackVersionMgr.getHotfixUpdateInfo(packageMark);
        if(null == hotfixUpdateInfo){
            needOldDeal = true;
        }else {
            if (isWhiteUser) {
                if(StringUtils.isNullOrEmpty(hotfixUpdateInfo.getWhiteUpdateVersion())){
                    needOldDeal = true;
                }
            } else if (forwardServer > 0) {
                if(StringUtils.isNullOrEmpty(hotfixUpdateInfo.getForwardUpdateVersion())){
                    needOldDeal = true;
                }
            } else {
                if(StringUtils.isNullOrEmpty(hotfixUpdateInfo.getUpdateVersion())){
                    needOldDeal = true;
                }
            }
        }
        return needOldDeal;
    }
}
